import { Component, Input, Output, OnInit, EventEmitter, forwardRef } from '@angular/core'
import { typeofExpr } from '@angular/compiler/src/output/output_ast'
import { FormsModule, NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'
@Component({
  selector: 'app-input-range',
  templateUrl: './input-range.component.html',
  styleUrls: ['./input-range.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => InputRangeComponent),
      multi: true
    }
  ]
})
export class InputRangeComponent implements OnInit, ControlValueAccessor {
  @Input()
  public unit = ''
  @Input()
  public minvalue = ''
  @Input()
  public maxvalue = ''
  @Input()
  public value: any[2] = [0, 0]
  @Output('ngModelChange')

  public update = new EventEmitter<any>()
  public valueData = []
  public minNum: any = ''
  public maxNum: any = ''
  public eventFlag: any = ''
  public onInputMinBlur = this.onInputBlurmin().bind(this)
  public onInputMaxBlur = this.onInputBlurmax().bind(this)
  constructor() {}

  writeValue(val: object): void {
    this.value = val
  }

  registerOnChange(fn: any): void {}

  registerOnTouched(fn: any): void {}

  ngOnInit() {
  }


  public onKeyPress(event: KeyboardEvent, value: string = '') {
    this.eventFlag = event
    const { keyCode } = event
    const range = [...Array.from(Array(10), (x, i) => i + 48), 13, 8, 189, 190]
    const checkList = [
      () => range.includes(keyCode),
      () => keyCode !== 190 || value.indexOf('.') === -1,
      () => keyCode !== 189 || value.length === 0
    ]

    if (!checkList.every(x => x())) {
      event.stopPropagation()
      event.preventDefault()
    }
  }

  public onInputBlurmin() {
    return function(eventNum) {
      this.minNum = parseFloat(eventNum)
      if (
        parseFloat(this.maxNum) <= parseFloat(this.minNum) ||
        parseFloat(this.minNum) < parseFloat(this.minvalue) ||
        isNaN(this.minNum)
      ) {
        this.minNum = ''
      }
      this.writeValue([this.minNum, this.maxNum])
      this.update.emit(this.value)
    }
  }

  public onInputBlurmax() {
    return function(eventNum) {
      this.maxNum = parseFloat(eventNum)
      if (
        parseFloat(this.maxNum) <= parseFloat(this.minNum) ||
        parseFloat(this.maxNum) > parseFloat(this.maxvalue) ||
        isNaN(this.maxNum)
      ) {
        this.maxNum = ''
      }
      this.writeValue([this.minNum, this.maxNum])
      this.update.emit(this.value)
    }
  }
}
